import { getToken, setToken, removeToken } from "@/utils/auth";
import { login, getUserInfo } from "@/api/user";
const state = {
  token: getToken(),
  userInfo: {},
};
const mutations = {
  setToken(state, token) {
    state.token = token;
    // 同步到缓存
    setToken(token);
  },
  // 删除token（vuex+缓存的token）
  removeToken(state) {
    state.token = null;
    removeToken();
  },
  //修改用户信息
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo;
  },
};
const actions = {
  // 登录的回调
  async login(context, data) {
    const token = await login(data);
    context.commit("setToken", token);
  },
  // 获取用户的资料
  async getUserInfo(context) {
    const res = await getUserInfo();
    context.commit("setUserInfo", res);
  },
  // 退出登录
  logout(context) {
    context.commit("removeToken");
    context.commit("setUserInfo", {}); //设置用户信息为空对象
  },
};
export default {
  namespaced: true, //开启命名空间
  state,
  mutations,
  actions,
};
